from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from Task.TaskProcessor import Init_Task
from Util.SQL import *
from Util.Return import *


@csrf_exempt
def tackle(request, nid, jud):                                              #nid为scene_id,后续还需传入需要执行的任务的id
    scene_id = nid
    result = select("SELECT id,model_name,date,state FROM task")
    for item in result:
        if 'date' in item:
            item['date'] = str(item['date'])[:10]
    result = result[::-1]
    if request.method == "GET":
        print(nid)
        # ori_string = "SELECT scene_id FROM data WHERE data_id = @"
        # sql_string = ori_string.replace("@", str(nid))
        # scene_id = select(sql_string)
        print(scene_id)
        img = 1
        if len(scene_id) != 0:
            img = get_image('available', scene_id)
            if img is None:
                img = 1
        if jud == 0:            #第一次进入该界面
            task = select("SELECT model_name FROM model")
            context = {"task": task, "img": img, "nid": nid, "result": result}
            print(context)
            return render(request, 'tackle.html', context)
        elif jud == 1:          #原来就在该界面
            context = {"img": img, "nid": nid}
            print(context)
            return JsonResponse(context)
    # ori_string = "SELECT scene_id FROM data WHERE data_id = @"
    # sql_string = ori_string.replace("@", str(nid))
    # scene_id = select(sql_string)
    Init_Task(scene_id, 'CWSAM')                    #暂且只对一个模型处理
    context = {"result": result, "nid": nid}
    return JsonResponse(context)


def tackle0(request):                                                        #直接从外部打开tackle网页
    result = select("SELECT id,model_name,date,state FROM task")
    for item in result:
        if 'date' in item:
            item['date'] = str(item['date'])[:10]
    result = result[::-1]
    task = select("SELECT model_name FROM model")
    print(task)
    context = {"task": task, "nid": -1, "result": result}
    # request.session['content'] = context
    return render(request, 'tackle.html', context)
